package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"backend/api"
	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FundScoreCardLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFundScoreCardLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FundScoreCardLogic {
	return &FundScoreCardLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FundScoreCardLogic) GetFundScoreCard(req *types.FundScoreCardReq) (resp *types.FundScoreCardResp, err error) {
	// 从数据库获取基金评分数据
	fundScore, err := l.svcCtx.FundScoreModel.FindByCode(l.ctx, req.FundCode)
	if err != nil {
		return nil, err
	}

	// 解析雷达图标签和值
	var radarLabels []string
	var radarValues []int32

	if err := json.Unmarshal([]byte(fundScore.RadarLabels), &radarLabels); err != nil {
		return nil, err
	}
	if err := json.Unmarshal([]byte(fundScore.RadarValues), &radarValues); err != nil {
		return nil, err
	}

	// 格式化日期
	establishedStr := fundScore.Established.Format("2006-01-02")

	// 解析成立日期
	parts := strings.Split(establishedStr, "-")
	var estYear, estMonth, estDay string
	if len(parts) == 3 {
		estYear = parts[0]
		estMonth = parts[1]
		estDay = parts[2]
	}

	// 构造响应
	resp = &types.FundScoreCardResp{
		Name:        fundScore.FundName,
		Code:        fundScore.FundCode,
		Type:        fundScore.FundType,
		Risk:        fundScore.RiskLevel,
		Manager:     fundScore.Manager,
		Company:     fundScore.Company,
		Size:        fundScore.Size,
		Established: establishedStr,
		TotalScore:  fundScore.TotalScore,
		ScoreType:   fundScore.ScoreType,
		Profit:      fundScore.ProfitScore,
		ProfitDesc:  fundScore.ProfitDesc,
		RiskScore:   fundScore.RiskScore,
		RiskDesc:    fundScore.RiskDesc,
		Stable:      fundScore.StableScore,
		StableDesc:  fundScore.StableDesc,
		RiskTip:     fundScore.RiskTip,
		RadarLabels: radarLabels,
		RadarValues: radarValues,
		Growth:      "450%", // 默认成立以来涨幅值，实际项目中应从数据库获取
		EstYear:     estYear,
		EstMonth:    estMonth,
		EstDay:      estDay,
	}

	return resp, nil
}

// 用于测试的模拟数据，可以在没有数据库数据时使用
func (l *FundScoreCardLogic) GetMockFundScoreCard(code string) *types.FundScoreCardResp {
	// 从真实API获取基金数据
	fundDetailInfo, err := api.GetFundDetail(code, "")
	if err == nil && fundDetailInfo != nil {
		logx.Infof("成功从API获取基金[%s]数据", code)
		
		// 提取绩效数据
		fundPerf := api.GetFundPerformanceFromDetail(fundDetailInfo)
		
		// 计算评分
		totalScore := int32(70)
		profitScore := int32(60)
		riskScore := int32(60)
		stableScore := int32(60)
		
		// 根据业绩计算评分
		yearGrowth := parseFloat(fundDetailInfo.LastYearGrowth)
		threeMonthGrowth := parseFloat(fundDetailInfo.LastThreeMonthsGrowth)
		
		// 增长情况影响赚钱能力评分
		if yearGrowth > 20 {
			profitScore += 30
			totalScore += 15
		} else if yearGrowth > 10 {
			profitScore += 20
			totalScore += 10
		} else if yearGrowth > 0 {
			profitScore += 10
			totalScore += 5
		} else if yearGrowth < -10 {
			profitScore -= 10
			totalScore -= 5
		}
		
		if threeMonthGrowth > 10 {
			profitScore += 10
			totalScore += 5
		} else if threeMonthGrowth < -10 {
			profitScore -= 10
			totalScore -= 5
		}
		
		// 波动率和最大回撤影响风险评分
		if fundPerf.MaxDrawdown < 0.15 {
			riskScore += 25
			totalScore += 10
		} else if fundPerf.MaxDrawdown < 0.25 {
			riskScore += 10
			totalScore += 5
		} else if fundPerf.MaxDrawdown > 0.35 {
			riskScore -= 15
			totalScore -= 5
		}
		
		if fundPerf.Volatility < 0.15 {
			riskScore += 15
			stableScore += 15
			totalScore += 8
		} else if fundPerf.Volatility > 0.3 {
			riskScore -= 10
			stableScore -= 10
			totalScore -= 5
		}
		
		// 夏普比率影响稳定性评分
		if fundPerf.SharpRatio > 1.0 {
			stableScore += 20
			totalScore += 10
		} else if fundPerf.SharpRatio > 0.5 {
			stableScore += 10
			totalScore += 5
		} else if fundPerf.SharpRatio < 0 {
			stableScore -= 10
			totalScore -= 5
		}
		
		// 限制评分范围
		totalScore = limitScore(totalScore)
		profitScore = limitScore(profitScore)
		riskScore = limitScore(riskScore)
		stableScore = limitScore(stableScore)
		
		// 根据总评分确定类型
		scoreType := determineScoreType(totalScore)
		
		// 生成描述文本
		profitDesc := generateProfitDescFromRealData(fundDetailInfo)
		riskDesc := generateRiskDescFromRealData(fundDetailInfo, fundPerf)
		stableDesc := generateStableDescFromRealData(fundDetailInfo, fundPerf)
		
		// 确定风险等级
		riskLevel := determineRiskLevel(fundDetailInfo.Type, fundPerf.Volatility)
		
		// 解析成立日期
		establishedDate := formatEstablishDate(fundDetailInfo.NetWorthData)
		parts := strings.Split(establishedDate, "-")
		var estYear, estMonth, estDay string
		if len(parts) == 3 {
			estYear = parts[0]
			estMonth = parts[1]
			estDay = parts[2]
		}
		
		// 返回结果
		return &types.FundScoreCardResp{
			Name:        fundDetailInfo.Name,
			Code:        fundDetailInfo.Code,
			Type:        fundDetailInfo.Type,
			Risk:        riskLevel,
			Manager:     fundDetailInfo.Manager,
			Company:     extractCompany(fundDetailInfo.Manager),
			Size:        fundDetailInfo.FundScale,
			Established: establishedDate,
			TotalScore:  totalScore,
			ScoreType:   scoreType,
			Profit:      profitScore,
			ProfitDesc:  profitDesc,
			RiskScore:   riskScore,
			RiskDesc:    riskDesc,
			Stable:      stableScore,
			StableDesc:  stableDesc,
			RiskTip:     generateRiskTip(fundDetailInfo, fundPerf),
			RadarLabels: []string{"赚钱能力", "抗跌能力", "稳定性", "最大回撤"},
			RadarValues: []int32{profitScore, riskScore, stableScore, int32(100 - int32(fundPerf.MaxDrawdown*100))},
			Growth:      "450%", // 默认成立以来涨幅值
			EstYear:     estYear,
			EstMonth:    estMonth,
			EstDay:      estDay,
		}
	}

	// 尝试从AKShare获取基金数据
	fundInfo, err := api.GetFundBaseInfo(code)
	if err == nil && fundInfo != nil {
		// 获取基金业绩数据
		fundPerf, err := api.GetFundPerformance(code)
		if err == nil && fundPerf != nil {
			// 根据性能数据计算评分
			totalScore := int32(70)
			profitScore := int32(60)
			riskScore := int32(60)
			stableScore := int32(60)
			
			// 计算总评分
			if fundPerf.ThreeYear > 0.3 {
				totalScore += 20
				profitScore += 30
			} else if fundPerf.ThreeYear > 0.15 {
				totalScore += 10
				profitScore += 20
			} else if fundPerf.ThreeYear > 0 {
				totalScore += 5
				profitScore += 10
			}
			
			if fundPerf.MaxDrawdown < 0.1 {
				totalScore += 15
				riskScore += 30
			} else if fundPerf.MaxDrawdown < 0.2 {
				totalScore += 5
				riskScore += 20
			} else if fundPerf.MaxDrawdown > 0.3 {
				totalScore -= 10
				riskScore -= 10
			}
			
			if fundPerf.Volatility < 0.1 {
				totalScore += 10
				stableScore += 30
			} else if fundPerf.Volatility < 0.2 {
				totalScore += 5
				stableScore += 15
			} else if fundPerf.Volatility > 0.3 {
				totalScore -= 5
				stableScore -= 10
			}
			
			if fundPerf.SharpRatio > 1.0 {
				totalScore += 10
				profitScore += 15
				riskScore += 10
			} else if fundPerf.SharpRatio > 0.5 {
				totalScore += 5
				profitScore += 10
				riskScore += 5
			}
			
			// 限制评分范围
			if totalScore > 100 {
				totalScore = 100
			} else if totalScore < 0 {
				totalScore = 0
			}
			
			if profitScore > 100 {
				profitScore = 100
			} else if profitScore < 0 {
				profitScore = 0
			}
			
			if riskScore > 100 {
				riskScore = 100
			} else if riskScore < 0 {
				riskScore = 0
			}
			
			if stableScore > 100 {
				stableScore = 100
			} else if stableScore < 0 {
				stableScore = 0
			}
			
			// 计算评分类型
			scoreType := "均衡型"
			if totalScore >= 85 {
				scoreType = "进取型"
			} else if totalScore >= 75 {
				scoreType = "稳健型"
			} else if totalScore >= 65 {
				scoreType = "保守型"
			} else {
				scoreType = "谨慎型"
			}
			
			// 生成描述
			profitDesc := generateProfitDescFromPerf(fundPerf)
			riskDesc := generateRiskDescFromPerf(fundPerf)
			stableDesc := generateStableDescFromInfo(fundInfo, fundPerf)
			
			// 雷达图数据
			radarLabels := []string{"赚钱能力", "抗跌能力", "稳定性", "最大回撤"}
			radarValues := []int32{profitScore, riskScore, stableScore, int32(100 - int32(fundPerf.MaxDrawdown*100))}
			
			// 解析成立日期
			parts := strings.Split(fundInfo.Established, "-")
			var estYear, estMonth, estDay string
			if len(parts) == 3 {
				estYear = parts[0]
				estMonth = parts[1]
				estDay = parts[2]
			}
			
			// 返回完整结构
			return &types.FundScoreCardResp{
				Name:        fundInfo.Name,
				Code:        fundInfo.Code,
				Type:        fundInfo.Type,
				Risk:        getRiskLevelFromType(fundInfo.Type),
				Manager:     fundInfo.Manager,
				Company:     fundInfo.Company,
				Size:        fundInfo.Size,
				Established: fundInfo.Established,
				TotalScore:  totalScore,
				ScoreType:   scoreType,
				Profit:      profitScore,
				ProfitDesc:  profitDesc,
				RiskScore:   riskScore,
				RiskDesc:    riskDesc,
				Stable:      stableScore,
				StableDesc:  stableDesc,
				RiskTip:     "服务方法的推荐仅为参考，对过去的表现不代表未来，不代表对投资收益的保证或承诺",
				RadarLabels: radarLabels,
				RadarValues: radarValues,
				Growth:      "450%", // 默认成立以来涨幅值
				EstYear:     estYear,
				EstMonth:    estMonth,
				EstDay:      estDay,
			}
		}
	}

	// 如果API调用失败或没有数据，则使用硬编码的数据
	if code == "003504" {
		// 解析成立日期
		establishedDate := "2017-01-18"
		parts := strings.Split(establishedDate, "-")
		var estYear, estMonth, estDay string
		if len(parts) == 3 {
			estYear = parts[0]
			estMonth = parts[1]
			estDay = parts[2]
		}
		
		return &types.FundScoreCardResp{
			Name:        "景顺长城景颐混合丰利A",
			Code:        "003504",
			Type:        "混合型基金",
			Risk:        "中风险",
			Manager:     "陈威卿",
			Company:     "景顺长城基金",
			Size:        "12.63亿元",
			Established: establishedDate,
			TotalScore:  82,
			ScoreType:   "稳健型",
			Profit:      84,
			ProfitDesc:  "过去3年跑赢了同类平均收益率\n过去3年跑赢了沪深300指数收益率\n最近1个月90%，排在同类前70%（超额收益）",
			RiskScore:   72,
			RiskDesc:    "过去3年波动了比同类小波动\n过去3年跌过了比同类小跌幅\n投过了29%300，远好于55%的同类产品",
			Stable:      94,
			StableDesc:  "基金经理优秀，经历过4个熊市周期\n过去3年换手120%，换手频率中等77%\n经理自下而上，基金特色是稳健且强安全性",
			RiskTip:     "服务方法的推荐仅为理财人工智能的建议生成，对过去的表现仅为选择优质产品参考，不代表对投资收益的保证或承诺",
			RadarLabels: []string{"赚钱能力", "抗跌能力", "稳定性", "最大回撤"},
			RadarValues: []int32{84, 72, 94, 69},
			Growth:      "450%",
			EstYear:     estYear,
			EstMonth:    estMonth,
			EstDay:      estDay,
		}
	}

	// 默认数据
	establishedDate := time.Now().AddDate(-5, 0, 0).Format("2006-01-02")
	parts := strings.Split(establishedDate, "-")
	var estYear, estMonth, estDay string
	if len(parts) == 3 {
		estYear = parts[0]
		estMonth = parts[1]
		estDay = parts[2]
	}

	return &types.FundScoreCardResp{
		Name:        "示例基金",
		Code:        code,
		Type:        "混合型基金",
		Risk:        "中风险",
		Manager:     "张三",
		Company:     "样例基金管理有限公司",
		Size:        "10.5亿元",
		Established: establishedDate,
		TotalScore:  75,
		ScoreType:   "稳健型",
		Profit:      80,
		ProfitDesc:  "过去3年跑赢了同类平均收益率\n过去3年跑赢了沪深300指数收益率",
		RiskScore:   70,
		RiskDesc:    "过去3年波动了比同类小波动\n过去3年跌过了比同类小跌幅",
		Stable:      75,
		StableDesc:  "基金经理优秀，经历过3个熊市周期\n过去3年换手100%，换手频率适中",
		RiskTip:     "服务方法的推荐仅为参考，对过去的表现不代表未来，不代表对投资收益的保证或承诺",
		RadarLabels: []string{"赚钱能力", "抗跌能力", "稳定性", "最大回撤"},
		RadarValues: []int32{80, 70, 75, 65},
		Growth:      "320%",
		EstYear:     estYear,
		EstMonth:    estMonth,
		EstDay:      estDay,
	}
}

// 从字符串解析浮点数
func parseFloat(s string) float64 {
	var f float64
	fmt.Sscanf(s, "%f%%", &f)
	return f
}

// 限制评分在0-100范围内
func limitScore(score int32) int32 {
	if score > 100 {
		return 100
	}
	if score < 0 {
		return 0
	}
	return score
}

// 根据总评分确定类型
func determineScoreType(totalScore int32) string {
	if totalScore >= 85 {
		return "进取型"
	} else if totalScore >= 75 {
		return "稳健型"
	} else if totalScore >= 65 {
		return "均衡型"
	} else if totalScore >= 50 {
		return "保守型"
	}
	return "谨慎型"
}

// 确定风险等级
func determineRiskLevel(fundType string, volatility float64) string {
	if strings.Contains(fundType, "货币") {
		return "低风险"
	} else if strings.Contains(fundType, "债券") {
		return "中低风险"
	} else if strings.Contains(fundType, "混合") {
		if volatility > 0.25 {
			return "中高风险"
		}
		return "中风险"
	} else if strings.Contains(fundType, "指数") {
		return "中高风险"
	} else if strings.Contains(fundType, "股票") {
		return "高风险"
	}
	return "中风险"
}

// 从基金经理信息提取公司
func extractCompany(managerInfo string) string {
	// 通常格式为: "张三 - XX基金公司"
	if strings.Contains(managerInfo, "-") {
		parts := strings.Split(managerInfo, "-")
		if len(parts) > 1 {
			return strings.TrimSpace(parts[1])
		}
	}
	return "未知公司"
}

// 从净值数据获取成立日期
func formatEstablishDate(netWorthData [][]string) string {
	if len(netWorthData) > 0 && len(netWorthData[len(netWorthData)-1]) > 0 {
		// 最后一条记录通常是最早的数据
		return netWorthData[len(netWorthData)-1][0]
	}
	return time.Now().AddDate(-5, 0, 0).Format("2006-01-02")
}

// 生成赚钱能力描述（基于真实数据）
func generateProfitDescFromRealData(fundDetail *api.FundDetail) string {
	var desc strings.Builder
	
	// 年增长率
	yearGrowth := parseFloat(fundDetail.LastYearGrowth)
	if yearGrowth > 0 {
		desc.WriteString(fmt.Sprintf("过去1年收益率%.2f%%", yearGrowth))
		if yearGrowth > 20 {
			desc.WriteString("，表现极为优秀\n")
		} else if yearGrowth > 10 {
			desc.WriteString("，表现优秀\n")
		} else {
			desc.WriteString("，表现良好\n")
		}
	} else {
		desc.WriteString(fmt.Sprintf("过去1年收益率%.2f%%，表现一般\n", yearGrowth))
	}
	
	// 最近三个月增长率
	threeMonthGrowth := parseFloat(fundDetail.LastThreeMonthsGrowth)
	if threeMonthGrowth > 0 {
		desc.WriteString(fmt.Sprintf("最近三个月收益率%.2f%%", threeMonthGrowth))
		if threeMonthGrowth > 10 {
			desc.WriteString("，近期表现强劲\n")
		} else {
			desc.WriteString("，近期表现稳健\n")
		}
	} else {
		desc.WriteString(fmt.Sprintf("最近三个月收益率%.2f%%，近期表现一般\n", threeMonthGrowth))
	}
	
	// 最近一个月增长率
	dayGrowth := parseFloat(fundDetail.DayGrowth)
	desc.WriteString(fmt.Sprintf("最近一日增长率%.2f%%", dayGrowth))
	if dayGrowth > 1 {
		desc.WriteString("，近期走势向好")
	} else if dayGrowth < -1 {
		desc.WriteString("，短期有所波动")
	} else {
		desc.WriteString("，短期表现平稳")
	}
	
	return desc.String()
}

// 生成风险控制描述（基于真实数据）
func generateRiskDescFromRealData(fundDetail *api.FundDetail, perf *api.FundPerformance) string {
	var desc strings.Builder
	
	// 最大回撤
	desc.WriteString(fmt.Sprintf("最大回撤为%.2f%%", perf.MaxDrawdown*100))
	if perf.MaxDrawdown < 0.15 {
		desc.WriteString("，控制良好\n")
	} else if perf.MaxDrawdown < 0.25 {
		desc.WriteString("，属于行业平均水平\n")
	} else {
		desc.WriteString("，历史波动较大\n")
	}
	
	// 波动率
	desc.WriteString(fmt.Sprintf("波动率为%.2f%%", perf.Volatility*100))
	if perf.Volatility < 0.15 {
		desc.WriteString("，属于低波动产品\n")
	} else if perf.Volatility < 0.25 {
		desc.WriteString("，波动性中等\n")
	} else {
		desc.WriteString("，波动较大\n")
	}
	
	// 夏普比率
	desc.WriteString(fmt.Sprintf("夏普比率为%.2f", perf.SharpRatio))
	if perf.SharpRatio > 1 {
		desc.WriteString("，风险调整后收益优秀")
	} else if perf.SharpRatio > 0.5 {
		desc.WriteString("，风险调整后收益尚可")
	} else if perf.SharpRatio > 0 {
		desc.WriteString("，风险收益比一般")
	} else {
		desc.WriteString("，风险收益比较低")
	}
	
	return desc.String()
}

// 生成稳定性描述（基于真实数据）
func generateStableDescFromRealData(fundDetail *api.FundDetail, perf *api.FundPerformance) string {
	var desc strings.Builder
	
	// 基金经理
	desc.WriteString(fmt.Sprintf("基金经理: %s\n", fundDetail.Manager))
	
	// 基金规模
	desc.WriteString(fmt.Sprintf("基金规模: %s\n", fundDetail.FundScale))
	
	// 成立至今表现
	if len(fundDetail.NetWorthData) > 0 {
		desc.WriteString("基金成立以来经历市场波动，")
		if perf.FromStart > 0.5 {
			desc.WriteString("总体表现优秀，长期收益稳健\n")
		} else if perf.FromStart > 0.2 {
			desc.WriteString("总体表现良好，长期回报稳定\n")
		} else if perf.FromStart > 0 {
			desc.WriteString("总体表现一般，波动中有所收益\n")
		} else {
			desc.WriteString("总体表现尚需观察，回报有待提升\n")
		}
	}
	
	// 综合稳定性评价
	if perf.MaxDrawdown < 0.2 && perf.Volatility < 0.2 {
		desc.WriteString("基金整体表现稳健，抗风险能力强")
	} else if perf.MaxDrawdown < 0.3 && perf.Volatility < 0.3 {
		desc.WriteString("基金抗风险能力一般，波动中能维持基本稳定")
	} else {
		desc.WriteString("基金历史波动较大，建议投资者关注风险")
	}
	
	return desc.String()
}

// 生成风险提示信息
func generateRiskTip(fundDetail *api.FundDetail, perf *api.FundPerformance) string {
	var riskTip string
	
	if perf.Volatility > 0.25 || perf.MaxDrawdown > 0.3 {
		riskTip = "该基金历史波动较大，建议投资者做好长期投资准备（建议3年以上），短期可能面临较大波动。过往业绩不代表未来表现，投资需谨慎。"
	} else if perf.Volatility > 0.15 || perf.MaxDrawdown > 0.2 {
		riskTip = "该基金波动性中等，建议中长期持有（1-3年），市场波动期间可能出现回撤。过往业绩不代表未来表现，投资需谨慎。"
	} else {
		riskTip = "该基金历史波动相对较小，但金融市场存在不确定性，投资者仍需关注风险。过往业绩不代表未来表现，投资需谨慎。"
	}
	
	return riskTip
}

// FundInfo 结构体用于存储从API获取的基金信息
type FundInfo struct {
	Name         string  `json:"name"`
	CurrentValue float64 `json:"current_value"`
	ChangeRate   float64 `json:"change_rate"`
	YearReturn   float64 `json:"year_return"`
	ThreeYear    float64 `json:"three_year"`
	FiveYear     float64 `json:"five_year"`
	MaxDrawdown  float64 `json:"max_drawdown"`
	Volatility   float64 `json:"volatility"`
}

// 从外部API获取基金信息
func getFundInfoFromAPI(code string) (*FundInfo, string, string, string, string, string, error) {
	// 这里使用东方财富网API（模拟）
	url := fmt.Sprintf("https://api.example.com/fund/info?code=%s", code)
	
	// 发起HTTP请求
	resp, err := http.Get(url)
	if err != nil {
		return nil, "", "", "", "", "", err
	}
	defer resp.Body.Close()
	
	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, "", "", "", "", "", err
	}
	
	// 解析JSON响应
	var result struct {
		Success bool     `json:"success"`
		Data    FundInfo `json:"data"`
		Manager string   `json:"manager"`
		Company string   `json:"company"`
		Type    string   `json:"type"`
		Size    string   `json:"size"`
		EstDate string   `json:"established_date"`
	}
	
	if err := json.Unmarshal(body, &result); err != nil {
		return nil, "", "", "", "", "", err
	}
	
	if !result.Success {
		return nil, "", "", "", "", "", fmt.Errorf("API request failed")
	}
	
	return &result.Data, result.Manager, result.Company, result.Type, result.Size, result.EstDate, nil
}

// 计算各项评分
func calculateScores(fundInfo *FundInfo) (int32, int32, int32, int32) {
	// 计算总评分 (0-100)
	totalScore := int32(70 + fundInfo.YearReturn*2 - fundInfo.MaxDrawdown)
	if totalScore > 100 {
		totalScore = 100
	} else if totalScore < 0 {
		totalScore = 0
	}
	
	// 计算赚钱能力评分 (0-100)
	profitScore := int32(60 + fundInfo.ThreeYear*3 + fundInfo.YearReturn*3)
	if profitScore > 100 {
		profitScore = 100
	} else if profitScore < 0 {
		profitScore = 0
	}
	
	// 计算风险控制评分 (0-100)
	riskScore := int32(80 - fundInfo.MaxDrawdown*2 - fundInfo.Volatility)
	if riskScore > 100 {
		riskScore = 100
	} else if riskScore < 0 {
		riskScore = 0
	}
	
	// 计算稳定性评分 (0-100)
	stableScore := int32(70 + (fundInfo.FiveYear-fundInfo.MaxDrawdown)*2)
	if stableScore > 100 {
		stableScore = 100
	} else if stableScore < 0 {
		stableScore = 0
	}
	
	return totalScore, profitScore, riskScore, stableScore
}

// 根据总评分获取评分类型
func getScoreType(score int32) string {
	switch {
	case score >= 90:
		return "进取型"
	case score >= 80:
		return "稳健型"
	case score >= 70:
		return "均衡型"
	case score >= 60:
		return "保守型"
	default:
		return "谨慎型"
	}
}

// 获取风险等级
func getRiskLevel(fundType string) string {
	switch {
	case strings.Contains(fundType, "股票"):
		return "高风险"
	case strings.Contains(fundType, "混合"):
		return "中风险"
	case strings.Contains(fundType, "债券"):
		return "低风险"
	case strings.Contains(fundType, "货币"):
		return "极低风险"
	default:
		return "中风险"
	}
}

// 生成赚钱能力描述
func generateProfitDescFromPerf(perf *api.FundPerformance) string {
	var desc strings.Builder
	
	if perf.ThreeYear > 0 {
		desc.WriteString(fmt.Sprintf("过去3年收益率%.2f%%", perf.ThreeYear*100))
		if perf.ThreeYear > 0.3 {
			desc.WriteString("，表现优秀\n")
		} else if perf.ThreeYear > 0.15 {
			desc.WriteString("，表现良好\n")
		} else {
			desc.WriteString("，表现一般\n")
		}
	}
	
	if perf.YearReturn > 0 {
		desc.WriteString(fmt.Sprintf("近一年收益率%.2f%%", perf.YearReturn*100))
		if perf.YearReturn > 0.2 {
			desc.WriteString("，跑赢大盘\n")
		} else {
			desc.WriteString("，表现平稳\n")
		}
	}
	
	if perf.MonthReturn > 0 {
		desc.WriteString(fmt.Sprintf("近一个月收益率%.2f%%", perf.MonthReturn*100))
		if perf.MonthReturn > 0.05 {
			desc.WriteString("，阶段表现优异")
		} else {
			desc.WriteString("，保持稳定增长")
		}
	} else if perf.MonthReturn < 0 {
		desc.WriteString(fmt.Sprintf("近一个月收益率%.2f%%", perf.MonthReturn*100))
		desc.WriteString("，短期表现有所波动")
	}
	
	return desc.String()
}

// 生成风险控制描述
func generateRiskDescFromPerf(perf *api.FundPerformance) string {
	var desc strings.Builder
	
	desc.WriteString(fmt.Sprintf("最大回撤为%.2f%%", perf.MaxDrawdown*100))
	if perf.MaxDrawdown < 0.1 {
		desc.WriteString("，控制良好\n")
	} else if perf.MaxDrawdown < 0.2 {
		desc.WriteString("，在行业内处于中等水平\n")
	} else {
		desc.WriteString("，历史波动较大\n")
	}
	
	desc.WriteString(fmt.Sprintf("波动率为%.2f%%", perf.Volatility*100))
	if perf.Volatility < 0.15 {
		desc.WriteString("，较为稳定\n")
	} else {
		desc.WriteString("，波动明显\n")
	}
	
	desc.WriteString(fmt.Sprintf("夏普比率为%.2f", perf.SharpRatio))
	if perf.SharpRatio > 1.0 {
		desc.WriteString("，风险调整后收益优秀")
	} else if perf.SharpRatio > 0.5 {
		desc.WriteString("，风险调整后收益良好")
	} else if perf.SharpRatio > 0 {
		desc.WriteString("，风险调整后收益一般")
	} else {
		desc.WriteString("，风险收益比较低")
	}
	
	return desc.String()
}

// 根据基金信息和业绩生成稳定性描述
func generateStableDescFromInfo(info *api.FundBaseInfo, perf *api.FundPerformance) string {
	var desc strings.Builder
	
	desc.WriteString(fmt.Sprintf("基金经理：%s\n", info.Manager))
	
	if perf.FiveYear > 0 {
		desc.WriteString(fmt.Sprintf("基金成立以来收益率为%.2f%%", perf.FromStart*100))
		if perf.FromStart > 0.5 {
			desc.WriteString("，长期业绩稳健\n")
		} else if perf.FromStart > 0.2 {
			desc.WriteString("，长期表现尚可\n")
		} else {
			desc.WriteString("，长期表现平平\n")
		}
	}
	
	// 根据回撤和波动率评估稳定性
	if perf.MaxDrawdown < 0.15 && perf.Volatility < 0.15 {
		desc.WriteString("综合表现稳健，抗风险能力强")
	} else if perf.MaxDrawdown < 0.25 && perf.Volatility < 0.25 {
		desc.WriteString("综合表现中性，抗风险能力一般")
	} else {
		desc.WriteString("历史波动较大，建议关注风险")
	}
	
	return desc.String()
}

// 从基金类型确定风险等级
func getRiskLevelFromType(fundType string) string {
	if strings.Contains(fundType, "货币") {
		return "低风险"
	} else if strings.Contains(fundType, "债券") {
		return "中低风险"
	} else if strings.Contains(fundType, "混合") {
		return "中风险"
	} else if strings.Contains(fundType, "指数") {
		return "中高风险"
	} else if strings.Contains(fundType, "股票") {
		return "高风险"
	}
	return "中风险"
}